package client

import (
	"5-28zk/common/proto/doctor"
	"context"
	"fmt"
	"google.golang.org/grpc"
)

type Handler func(ctx context.Context, client doctor.DoctorClient) (interface{}, error)

func DoctorClient(ctx context.Context, handler Handler) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
	}
	defer conn.Close()
	// 2. 实例化gRPC客户端
	client := doctor.NewDoctorClient(conn)
	// 3.组装请求参数
	req, _ := handler(ctx, client)
	return req, nil
}

func Login(ctx context.Context, req *doctor.LoginReq) (*doctor.LoginResp, error) {
	client, err := DoctorClient(ctx, func(ctx context.Context, client doctor.DoctorClient) (interface{}, error) {
		login, err := client.Login(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*doctor.LoginResp), nil
}

func PatientList(ctx context.Context, req *doctor.PatientListReq) (*doctor.PatientListResp, error) {
	client, err := DoctorClient(ctx, func(ctx context.Context, client doctor.DoctorClient) (interface{}, error) {
		login, err := client.PatientList(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*doctor.PatientListResp), nil
}
func PatientShow(ctx context.Context, req *doctor.PatientShowReq) (*doctor.PatientShowResp, error) {
	client, err := DoctorClient(ctx, func(ctx context.Context, client doctor.DoctorClient) (interface{}, error) {
		login, err := client.PatientShow(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*doctor.PatientShowResp), nil
}
